package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.filePath}")
    private String filePath;
    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        System.out.println(filePath);
        String originalFilename = file.getOriginalFilename();
        //得到文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffixName;
        file.transferTo(new File(filePath + fileName));
        return R.success(fileName);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //输入流，通过输入流读取文件内容
        FileInputStream inputStream = new FileInputStream(new File(filePath + name));
        //输出流，通过输出流将文件写回浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");

//      int len = 0;
//      byte[] bytes = new byte[1024];
//      while ((len = fileInputStream.read(bytes)) != -1){
//          outputStream.write(bytes,0,len);
//          outputStream.flush();
//      }
        //内容从输入流复制到输出流
        IoUtil.copy(inputStream,outputStream);
        //关闭资源
        outputStream.close();
        inputStream.close();
    }
}

